package org.example.fboot.result;

import lombok.Data;
import org.example.fboot.annotation.ToString;

import java.io.Serializable;
import java.util.Objects;

/**
 * 返回参数
 * @param <T>
 */
@Data
public class Result<T> implements Serializable {
    private int code;
    private String msg;
    private T data;

    public Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(RequestStat stat, T data){
        this.code=stat.code;
        this.msg=stat.msg;
        this.data=data;
    }
    public static <T> Result<T> ok(T data) {
        return result(RequestStat.ok, data);
    }
    public static <T> Result<T> ok() {
        return ok(null);
    }

    public static Result<String> out() {
        return result(RequestStat.logout);
    }

    public static Result<String> result(RequestStat stat) {
        return result(stat,null);
    }
    public static <T> Result<T> result(RequestStat stat, T data) {
        return new Result<T>(stat, data);
    }
    public static <T> Result<T> msgResult(RequestStat stat,String msg) {
        return new Result<T>(stat.code,msg, null);
    }
    public static <T> Result<T> msgResult(RequestStat stat,String msg, T data) {
        return new Result<T>(stat.code,msg, data);
    }
    @Override
    public String toString() {
        String dataStr = null;
        if (data!=null) {
            Class<?> dataClass = data.getClass();
            if (data instanceof String str) {
                dataStr = "\"" + str + "\"";
            } else if (Objects.nonNull(dataClass.getAnnotation(ToString.class))) {
                dataStr = data.toString();
            }
        }
        return String.format("""
                {
                    "code": %d,
                    "msg" : "%s",
                    "date": %s
                }
                """, this.code, this.msg, dataStr);
    }

}
